#include "mybutton.h"
#include <QStylePainter>
#include <QStyleOptionButton>
#include <QMouseEvent>

MyButton::MyButton(QWidget *parent) : QPushButton(parent)
{
    setStyleSheet("QPushButton {"
                      "background-color: #D3D3D3;" // 灰色
                      "color: #424242;" // 蓝色
                      "border: none;"
                      "border-radius: 5px;"
                      "padding: 10px 20px;"
                      "font-weight: bold;"
                      "font-size: 16px;"
                      "}"
                      "QPushButton:hover {"
                      "background-color: #333333;"
                      "color: #1E88E5;"
                      "}"
                      "QPushButton:pressed {"
                      "background-color: #222222;"
                      "color: #1565C0;"
                      "}");
    this->timer = new QTimer(this);
    connect(this->timer, &QTimer::timeout, this, [=](){
        emit LongPress();
        this->timer->stop();
    });
}

void MyButton::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton)   //当为左键时，不仅执行原有的事件内容，同时启动定时器
    {
        this->timer->start(500);
    }
    QPushButton::mousePressEvent(event);
}

void MyButton::mouseReleaseEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton)
    {
        if(this->timer->isActive()) //如果定时器还在运行，说明此时为点击事件
        {
            this->timer->stop();    //关闭计时器
            emit MyClicked();
        }
        else //如果定时器停止运行，说明此时为长按事件
        {
            emit MyReleased();
        }
    }
    QPushButton::mouseReleaseEvent(event);
}
